package com.pro.app.controller;


import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pro.app.annotation.LoginUser;
import com.pro.core.util.ResponseUtil;
import com.pro.core.validator.NotNullValidator;
import com.pro.db.domain.BbsComment;
import com.pro.db.domain.BbsTopic;
import com.pro.db.domain.ProUser;
import com.pro.db.service.itf.IBbsCommentService;
import com.pro.db.service.itf.IBbsTopicService;
import com.pro.db.service.itf.IProUserService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

import static com.baidu.unbiz.fluentvalidator.ResultCollectors.toComplex;


/**
 * <p>
 * 回复表 前端控制器
 * </p>
 *
 * @author 王雷
 * @since 2020-01-07
 */
@RestController
@RequestMapping("/app/bbsComment")
public class AppBbsCommentController  {
    private final Log logger = LogFactory.getLog(AppBbsCommentController.class);

    @Autowired
    private IBbsCommentService bbsCommentService;

    @Autowired
    private IProUserService userService;
    @Autowired
    private IBbsTopicService bbsTopicService;

    /**
     * @apiDefine bbsComment 评论接口
     *
     */

    /**
     * @api {GET} /app/bbsComment/list 6.1 获取评论列表
     * @apiName bbsComment list
     * @apiGroup bbsComment
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {int} topicId 帖子id
     * @apiParam {int} [page] 页码
     * @apiParam {int} [size] 每页数量
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @GetMapping("/list")
    public Object list(@NotNull Integer topicId,@RequestParam(defaultValue = "1") Integer page,
                             @RequestParam(defaultValue = "10") Integer size) {
        Page<BbsComment> pageVo = new Page<>();
        pageVo.setCurrent(page);
        pageVo.setSize(size);
        IPage<BbsComment> pList = bbsCommentService.page(pageVo,
                new QueryWrapper<BbsComment>()
                        .eq("deleted",0)
                        .eq("topic_id",topicId)
                        .orderByDesc("add_time"));
        for(BbsComment comment : pList.getRecords()){
            ProUser user = userService.getById(comment.getCreateUserId());
            user.setPassword(null);
            comment.setUser(user);
        }

        Map<String, Object> data = new HashMap<>();
        data.put("total", pList.getTotal());
        data.put("items", pList.getRecords());
        return ResponseUtil.ok(data);
    }


    /**
     * @api {GET} /app/bbsComment/read 6.2 评论详情
     * @apiName bbsComment read
     * @apiGroup bbsComment
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {int} id 评论id
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @GetMapping("/read")
    public Object read(@NotNull Integer id) {
        BbsComment entity = bbsCommentService.getById(id);
        return ResponseUtil.ok(entity);
    }

    /**
     * @api {POST} /app/bbsComment/create 6.3 新增评论
     * @apiName bbsComment create
     * @apiGroup bbsComment
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {int} topicId 帖子id
     * @apiParam {String} content 评论内容
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @PostMapping("/create")
    public Object create(@NotNull @LoginUser Integer userId, @RequestBody BbsComment entity) {
        ComplexResult check = FluentValidator.checkAll()
                .on(entity, new NotNullValidator("评论"))
                .on(entity.getTopicId(), new NotNullValidator("帖子id"))
                .on(entity.getContent(), new NotNullValidator("评论内容"))
                .doValidate()
                .result(toComplex());
        if (!check.isSuccess()) {
            //参数校验不通过，直接返回结果并提示缺少哪些参数
            return ResponseUtil.fail(check.getErrors());
        }

        entity.setAddTime(LocalDateTime.now());
        ProUser user = userService.getById(userId);

        entity.setAddTime(LocalDateTime.now());
        entity.setCreateUserId(userId);
        entity.setCreateAvatar(user.getAvatar());
        entity.setCreateNickname(user.getNickname());
        entity.setCreateUsername(user.getUsername());
        BbsTopic topic= bbsTopicService.getById(entity.getTopicId());
        entity.setSiteId(topic.getSiteId());
        entity.setForumId(topic.getForumId());
        entity.setDeleted(false);
        bbsCommentService.saveComment(entity);
        return ResponseUtil.ok();
    }

    /**
     * @api {POST} /app/bbsComment/update 6.4 更新评论
     * @apiName  bbsComment update
     * @apiGroup  bbsComment
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {int} id 评论id
     * @apiParam {String} content 评论内容
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @PostMapping("/update")
    public Object update(@NotNull @LoginUser Integer userId,@RequestBody  BbsComment entity) {
        ComplexResult check = FluentValidator.checkAll()
                .on(entity, new NotNullValidator("评论"))
                .on(entity.getId(), new NotNullValidator("评论ID"))
                .on(entity.getContent(), new NotNullValidator("评论内容"))
                .doValidate()
                .result(toComplex());
        if (!check.isSuccess()) {
            //参数校验不通过，直接返回结果并提示缺少哪些参数
            return ResponseUtil.fail(check.getErrors());
        }

        entity.setUpdateTime(LocalDateTime.now());
        entity.setDeleted(false);
        bbsCommentService.updateById(entity);
        return ResponseUtil.ok();
    }

    /**
     * @api {POST} /app/bbsComment/delete 6.5 删除评论
     * @apiName bbsComment delete
     * @apiGroup bbsComment
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {int} id 评论id
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @PostMapping("/delete")
    public Object delete(@NotNull @LoginUser Integer userId,@RequestBody BbsComment entity) {
        Integer id = entity.getId();
        if (id == null) {
            return ResponseUtil.fail("ID不能为空");
        }

        if(entity.getCreateUserId().equals(userId)){
            return ResponseUtil.fail("不是您的评论");
        }

        bbsCommentService.removeById(id);
        return ResponseUtil.ok();
    }

}

